﻿using System;
using System.Linq;
using ggHD.DAL.Repositories;
using ggHD.Domain.BizObj;
using ggHD.Domain.Repisitories;
using LinqToDB;

namespace DAL.Repositories
{
    public class Repository<TEntity, TKey> : IRepository<TEntity, TKey>
        where TEntity : class, IEntity<TKey>
    {
        private readonly IDataContext _context;

        protected ITable<TEntity> _entity;

        //public ggHDDB DbInstance
        //{
        //    get
        //    {
        //        return _context;
        //    }
        //}

        public Repository(IDataContext context)
        {
            _context = context;
            _entity = _context.GetTable<TEntity>();
        }

        public TEntity Get(TKey key)
        {
            return _entity.SingleOrDefault(e => e.Key.Equals(key));

            //return _context.GetTable<TEntity>().First(c => c.Key.Equals(key));
        }

        public IQueryable<TEntity> Select(Func<TEntity, bool> predicate)
        {
            return _entity.Where(predicate).AsQueryable();
        }

        public virtual int Insert(TEntity entity)
        {
            return _context.Insert(entity);
        }

        public virtual int Update(TEntity entity)
        {

            return _context.Update(entity);
        }

        public virtual int Delete(TKey key)
        {
            return _context.Delete(key);
        }

        public IQueryable<TEntity> All
        {
            get
            {
                return _entity.AsQueryable();
            }
        }
    }
}